const cheerio = require('cheerio');
const request = require('superagent');
const { __, filter, test, pipe, head, path, assoc } = require('ramda');
const slice = require('../utils/helpers').slice;

const getVideoContentURL = async (lesson) => {
    const res = await request.get(lesson.url);
    const $ = cheerio.load(res.text);
    const metaList = $('meta').attr('itemprop', 'contentURL');
    const metaArr = slice.call(metaList);

    const metaWithContentURL = (meta) => {
        const metaContent = path(['attribs', 'content'], meta);
        const pattern = /http:\/\/embed\.wistia\.com\/deliveries\/\w*\.bin/;

        return test(pattern, metaContent);
    };

    const getContentURL = pipe(
                            filter(metaWithContentURL),
                            head,
                            path(['attribs', 'content']),
                            assoc('contentURL', __, lesson));

    return getContentURL(metaArr);
};


// const lesson = {
//     title: 'refactor-to-point-free-functions-with-ramda-using-compose-and-converge',
//     url: 'https://egghead.io/lessons/javascript-refactor-to-point-free-functions-with-ramda-using-compose-and-converge?pl=learn-ramda-js-ec318ad7',
// };
//
// (async () => {
//     await getVideoContentURL(lesson);
// })();

module.exports = getVideoContentURL;
